import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import {
  TextInput,
  View,
  ScrollView,
  StyleSheet,
  Text,
  SafeAreaView,
  Image,
  Dimensions,
  Alert,
  PermissionsAndroid,
  TouchableOpacity,
  ImageBackground,
} from 'react-native';
import { NetworkInfo } from 'react-native-network-info';
import Overlay from '@/components/Overlay';
import { setUserInfo, setAuth } from '@/store/action/user';
import { login, queryUserMultiLoginConfig, getLoginConfig, loginDomain } from '@/apis/api';
import { Button, CheckBox } from '@rneui/themed';
import StorageUtils from '@/utils/storageUtils';
import * as rootNavigation from '@/utils/rootNavigation';
import { useTranslation } from 'react-i18next';
import { encrypt } from '@/utils/jsencrypt.js';

import { getLatestAppApkVersion, getLatestAppApkDownloadUrl } from '@/apis/api';
import RNFetchBlob from 'rn-fetch-blob';
import {
  APP_CODE as appCode,
  BASE_URL as baseUrl,
  DEVICE_TYPE as deviceType,
  APP_NAME as appName,
  VERSION_NAME as versionName,
} from '../../../app.json';
import Toast from 'react-native-root-toast';
import LanguageSwitcher from '@/components/LanguageSwitcher';

const { width } = Dimensions.get('window');
const formDefaultData = {
  userName: '',
  password: '',
  // remember: false,
};

// 域账号
const formDomainDefaultData = {
  userName: '',
  password: '',
  // remember: false,
};

function Form(props: any) {
  const { t } = useTranslation();
  const { setUserInfo, setAuth, lang } = props;
  const [formData, setFormData] = useState(formDefaultData);
  const [formDomainData, setFormDomainData] = useState(formDomainDefaultData);
  const [remember, setRemember] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isMultiLogin, setIsMultiLogin] = useState(false);
  const [ipAddr, setIpAddr] = useState('');
  const requestMultiplePermission = async () => {
    try {
      const permissions = [
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        PermissionsAndroid.PERMISSIONS.CAMERA,
        PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
      ];
      //返回得是对象类型
      const granteds = await PermissionsAndroid.requestMultiple(permissions);
      var data = '是否同意地址权限: ';
      if (granteds['android.permission.ACCESS_FINE_LOCATION'] === 'granted') {
        data = data + '是\n';
      } else {
        data = data + '否\n';
      }
      data = data + '是否同意相机权限: ';
      if (granteds['android.permission.CAMERA'] === 'granted') {
        data = data + '是\n';
      } else {
        data = data + '否\n';
      }
      data = data + '是否同意存储权限: ';
      if (granteds['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted') {
        data = data + '是\n';
        // 检查是否存在更新版本
        getLatestUpgradeVersion();
      } else {
        data = data + '否\n';
      }
      data = data + '是否同意通知权限: ';
      if (granteds['android.permission.POST_NOTIFICATIONS'] === 'granted') {
        data += '是\n';
      } else {
        data += '否\n';
      }
    } catch (err) { }
  };
  useEffect(() => {
    requestMultiplePermission();
    initLoginOption();
    showUserName();
    showDomainUserName();
  }, []);

  // 获取对应记住的用户名、密码
  const showUserName = async () => {
    const userName = await StorageUtils.getItem('userName');
    const userName_domain = await StorageUtils.getItem('userName_domain');
    const password = await StorageUtils.getItem('password');
    setFormData({
      ...formData,
      // 账号为纯数字 表单回显问题
      userName: (userName && typeof userName != 'string') ? JSON.stringify(userName) : userName,
      password,
      // remember: !!userName,
    });
    setRemember(!!userName || !!userName_domain || remember)
  };
  const showDomainUserName = async () => {
    const userName = await StorageUtils.getItem('userName');
    const userName_domain = await StorageUtils.getItem('userName_domain');
    const password_domain = await StorageUtils.getItem('password_domain');
    setFormDomainData({
      ...formDomainData,
      // 账号为纯数字 表单回显问题
      userName: (userName_domain && typeof userName_domain != 'string') ? JSON.stringify(userName_domain) : userName_domain,
      password: password_domain,
    });
    setRemember(!!userName || !!userName_domain || remember)
  };

  const handleLogin = async () => {
    setIsLoading(true);
    const res = await queryUserMultiLoginConfig({ username: formData.userName });
    let ipAddress = '';
    let hasMultiLogin = false;
    if (res?.data === 1) {
      setIsMultiLogin(true);
      hasMultiLogin = true;
      ipAddress = await NetworkInfo.getIPAddress();
      setIpAddr(ipAddress);
    }
    const params = { username: formData.userName, password: formData.password };
    if (ipAddress && hasMultiLogin) {
      params.device_ip = ipAddress;
    }
    try {
      let res = await login(params);
      const { user_id, username } = res;
      setAuth(res);
      // 密码登录 用户名、密码
      if (remember) {
        StorageUtils.setItem('userName', username);
        StorageUtils.setItem('password', formData.password);
      } else {
        clearRemember();
      }
      const userInfo = {
        user_id,
        username,
      };
      setUserInfo(userInfo);

      /**
       * 清空路由
       */
      rootNavigation.reset('Layout');
    } catch (err) {
    } finally {
      setIsLoading(false);
    }
  };
  // 域帐号登录
  const handleLoginDomain = async () => {
    setIsLoading(true);
    const params = { username: formDomainData.userName, password: encrypt(formDomainData.password), deviceType: 'MOBILE' };
    try {
      const res = await loginDomain(params);
      // TODO 确定后端返回数据格式
      const { user_id, username } = res?.data;
      setAuth(res?.data);
      if (remember) {
        StorageUtils.setItem('userName_domain', username);
        StorageUtils.setItem('password_domain', formDomainData.password);
      } else {
        clearRemember();
      }
      const userInfo = {
        user_id,
        username,
      };
      setUserInfo(userInfo);

      /**
       * 清空路由
       */
      rootNavigation.reset('Layout');
    } catch (error) {
    } finally {
      setIsLoading(false);
    }
  };

  const handleForgetPwd = () => {
    try {
      rootNavigation.navigate('PwdForget');
    } catch (err: any) {
      console.log(err);
      Alert.alert(t('sys_tip'), err.msg || err.message);
    }
  };

  const handleRemember = async () => {
    if (remember) {
      clearRemember()
    }
    setRemember(!remember)

  };

  const clearRemember = () => {
    StorageUtils.removeItem('userName');
    StorageUtils.removeItem('password');
    StorageUtils.removeItem('userName_domain');
    StorageUtils.removeItem('password_domain');
  }

  const [loginType, setLoginType] = useState('DomainLogin');
  const [loginOption, setLoginOption] = useState<Record<string, string | boolean>>({})
  // 获取登录配置
  const initLoginOption = async () => {
    const res = await getLoginConfig();
    const { configValue } = res.data;
    const { defaultLoginType, loginTypeList } = JSON.parse(configValue);
    setLoginType(defaultLoginType);
    let options = {};
    (loginTypeList || []).forEach((i) => {
      options[i.type] = i.enable;
    })
    setLoginOption(options);

  };
  // 切换登录方式
  const handleChangeType = (type) => {
    setLoginType(type)
    // setFormData({...formDefaultData})
    showUserName();
    showDomainUserName();
    setShowPassword(false);
  };

  const [showPassword, setShowPassword] = useState(false); // 控制密码是否可见

  const toggleShowPassword = () => {
    setShowPassword(!showPassword); // 切换密码可见性
  }

  const getLatestUpgradeVersion = async () => {
    const data = {
      appCode,
      baseUrl,
      deviceType,
      versionName,
    };

    // 获取最新的安装包版本
    const res = await getLatestAppApkVersion(data);
    const latestVersion = res?.data;

    if (res?.data && latestVersion !== versionName) {
      // 存在新版本
      Alert.alert(t('sys_tip'), t('sys_newVersionUpdateConfirm'), [
        {
          text: t('sys_cancel'),
          onPress: () => {},
          style: 'cancel',
        },
        {
          text: t('sys_update'),
          onPress: () => {
            download(res?.data);
          },
        },
      ]);
    }

  };

  const download = async (latestVersion: any) => {
    // const { t } = this.props;
    const params = {
      appCode,
      baseUrl,
      deviceType,
      versionName: latestVersion,
    };
    getLatestAppApkDownloadUrl(params).then(res => {
      if (res?.data) {
        // 指定包含最新版本的安装包文件的 URL
        const fileUrl = res?.data;
        const android = RNFetchBlob.android;
        let timestamp = new Date().getTime();
        // 文件保存路径
        const downloadDest = `${RNFetchBlob.fs.dirs.DownloadDir}/${appCode}-${timestamp}.apk`;
        Toast.show(t('sys_packageDownloadBackend'), {
          duration: 1000,
          position: Toast.positions.BOTTOM,
        });
        RNFetchBlob.config({
          fileCache: true,
          addAndroidDownloads: {
            useDownloadManager: true,
            // notification: true,
            mediaScannable: true,
            title: `${appCode}-${timestamp}.apk`,
            path: downloadDest,
          },
        })
          .fetch('GET', fileUrl, {})
          .then(res => {
            //下载成功后自动打开安装已下载apk文件
            android.actionViewIntent(
              res.path(),
              'application/vnd.android.package-archive',
            );
            console.log('The file saved to ', res.path());
          })
          .catch(error => {
            Toast.show(t('sys_fileDownloadFail'), {
              duration: 1000,
              position: Toast.positions.CENTER,
            });
          });
      }
    });
  };

  return (
    <ImageBackground
      source={require('@/assets/images/background.png')}
      style={styles.background}
      resizeMode="cover">
      <SafeAreaView style={styles.flex}>
        <Overlay isShow={isLoading} />
        <ScrollView contentContainerStyle={styles.contentContainer}>
          <View>
            <LanguageSwitcher />
          </View>
          <View>
            <View style={styles.logoForm}>
              <Text style={styles.logoText}>{t('sys_welcomLogin')}</Text>
              {/* <Text style={styles.tipText}>{t('sys_momText')}</Text> */}
              <Text style={styles.tipText}>{global.$config.APP_NAME}</Text>
            </View>
            {/* 账密登录 */}
            {loginType === 'PasswordLogin' && (<View>
              <Text style={styles.label}>{t('sys_username')}</Text>
              <TextInput
                placeholder={t('sys_usernameInputTip')}
                onChangeText={text =>
                  setFormData({
                    ...formData,
                    userName: text,
                  })
                }
                value={formData.userName}
                style={[styles.inputStyle]}
              />
              <Text style={styles.label}>{t('sys_password')}</Text>
              <View style={styles.passwordInputContainer}>
                <TextInput
                  style={[styles.passwordInput]}
                  placeholder={t('sys_plsInputPwd')}
                  onChangeText={text =>
                    setFormData({
                      ...formData,
                      password: text,
                    })
                  }
                  value={formData.password}
                  secureTextEntry={!showPassword} // 控制密码是否可见
                  autoCapitalize="none"
                />
                <TouchableOpacity onPress={toggleShowPassword} style={styles.eyeIcon}>
                  <Image
                    source={showPassword ? require('@/assets/images/eye_closed.png') : require('@/assets/images/eye_open.png')} // 替换为你的小眼睛图标路径
                    style={styles.eyeIconImage}
                  />
                </TouchableOpacity>
              </View>
              <View style={[styles.otherAction]}>
                <CheckBox
                  containerStyle={{
                    marginLeft: 0,
                    paddingLeft: 0,
                    backgroundColor: 'transparent',
                  }}
                  title={t('sys_rememberPassword')}
                  textStyle={styles.checkboxText}
                  iconType="material-community"
                  checked={remember}
                  checkedIcon="checkbox-outline"
                  uncheckedIcon={'checkbox-blank-outline'}
                  onPress={() => handleRemember()}
                />
                {loginType === 'PasswordLogin' && (<Button
                  title={t('sys_forgetPassword')}
                  titleStyle={styles.forgetPasswordText}
                  size="md"
                  type="clear"
                  onPress={handleForgetPwd}
                />)}
              </View>
              {/* 登录按钮 */}
              <TouchableOpacity style={[styles.buttonContainer, (!formData.userName || !formData.password) && styles.disabledButton]} disabled={!formData.userName || !formData.password} onPress={handleLogin}>
                <Image style={styles.buttonBackground} source={require('@/assets/images/button.png')}/>
                <Text style={styles.buttonText}>{t('sys_login')}</Text>
              </TouchableOpacity>
            </View>)}
            {/* 域帐号登录 */}
            {loginType === 'DomainLogin' && (<View>
              <Text style={styles.label}>{t('sys_username')}</Text>
              <TextInput
                placeholder={t('sys_plsAccount')}
                onChangeText={text =>
                  setFormDomainData({
                    ...formDomainData,
                    userName: text,
                  })
                }
                value={formDomainData.userName}
                style={[styles.inputStyle]}
              />
              <Text style={styles.label}>{t('sys_password')}</Text>
              <View style={styles.passwordInputContainer}>
                <TextInput
                  style={[styles.passwordInput]}
                  placeholder={t('sys_plsInputPwd')}
                  onChangeText={text =>
                    setFormDomainData({
                      ...formDomainData,
                      password: text,
                    })
                  }
                  value={formDomainData.password}
                  secureTextEntry={!showPassword} // 控制密码是否可见
                  autoCapitalize="none"
                />
                <TouchableOpacity onPress={toggleShowPassword} style={styles.eyeIcon}>
                  <Image
                    source={showPassword ? require('@/assets/images/eye_closed.png') : require('@/assets/images/eye_open.png')} // 替换为你的小眼睛图标路径
                    style={styles.eyeIconImage}
                  />
                </TouchableOpacity>
              </View>
              <View style={[styles.otherAction]}>
                <CheckBox
                  containerStyle={{
                    marginLeft: 0,
                    paddingLeft: 0,
                    backgroundColor: 'transparent',
                  }}
                  title={t('sys_rememberPassword')}
                  textStyle={styles.checkboxText}
                  iconType="material-community"
                  checked={remember}
                  checkedIcon="checkbox-outline"
                  uncheckedIcon={'checkbox-blank-outline'}
                  onPress={() => handleRemember()}
                />
              </View>
              {/* 登录按钮 */}
              <TouchableOpacity style={[styles.buttonContainer, (!formDomainData.userName || !formDomainData.password) && styles.disabledButton]} disabled={!formDomainData.userName || !formDomainData.password} onPress={handleLoginDomain}>
                <Image style={styles.buttonBackground} source={require('@/assets/images/button.png')}/>
                <Text style={styles.buttonText}>{t('sys_login')}</Text>
              </TouchableOpacity>
            </View>)}

          </View>
          <View style={styles.otherLoginContainer}>
            {(Object.keys(loginOption).filter((key) => loginOption[key] === true) || [])?.length > 1 && (<View style={styles.dividerContainer}>
              <View style={styles.dividerLine} />
              <Text>{t('sys_otherAccount')}</Text>
              <View style={styles.dividerLine} />
            </View>)}
            <View style={styles.otherLoginButtons}>

              {/* <TouchableOpacity style={styles.otherLoginButton} onPress={() => handleChangeType('WechatLogin')}>
                <Image source={require('@/assets/images/wechat.png')} style={styles.icon} />
              </TouchableOpacity> */}
              {loginType !== 'PasswordLogin' && loginOption.PasswordLogin && (<TouchableOpacity style={styles.otherLoginButton} onPress={() => handleChangeType('PasswordLogin')}>
                <Image source={require('@/assets/images/password.png')} style={styles.icon} />
              </TouchableOpacity>)}
              {loginType !== 'DomainLogin' && loginOption.DomainLogin && (<TouchableOpacity style={styles.otherLoginButton} onPress={() => handleChangeType('DomainLogin')}>
                <Image source={require('@/assets/images/accout_logo.png')} style={styles.icon} />
              </TouchableOpacity>)}
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
    </ImageBackground>
  );
}

export default connect(
  (state: any) => ({
    userInfo: state.user.userInfo,
    auth: state.user.auth,
    lang: state.lang
  }),
  dispatch => ({
    setUserInfo: (data: any) => dispatch(setUserInfo(data)),
    setAuth: (token: any) => dispatch(setAuth(token)),
  }),
)(Form);
const styles = StyleSheet.create({
  background: {
    display: 'flex',
    flex: 1,
  },
  flex: {
    display: 'flex',
    flex: 1,
  },
  contentContainer: {
    width: width * 0.85,
    display: 'flex',
    flex: 1,
    justifyContent: 'space-between',
    marginTop: 10,
    paddingBottom: 15,
    marginLeft: 'auto',
    marginRight: 'auto',
  },
  logoForm: {
    marginTop: 65,
  },
  logoText: {
    fontSize: 25,
    color: '#000000e6',
    marginBottom: 10,
  },
  tipText: {
    fontSize: 15,
    color: '#00000099',
    marginBottom: 20,
  },
  borderStyle: {
    borderColor: '#cacaca',
    borderWidth: 1,
  },
  otherAction: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  checkboxText: {
    fontSize: 12, // 字体大小
  },
  forgetPasswordText: {
    fontSize: 12, // 字体大小
  },
  label: {
    fontSize: 15,
    // marginBottom: 5,
    marginTop: 10,
    color: '#000000e6',
  },
  inputStyle: {
    height: 40,
    borderBottomWidth: 1, // 底部边框
    borderBottomColor: '#ccccccff', // 底部边框颜色
  },
  buttonContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 10,
    position: 'relative',
  },
  buttonBackground: {
    width: '100%',
    height: 75,
    resizeMode: 'cover',
    paddingLeft: 10,
    paddingRight: 10,
    // marginTop: 25,
  },
  disabledButton: {
    opacity: 0.5, // 禁用时降低透明度
  },
  buttonText: {
    position: 'absolute',
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
    top: 10
  },
  otherLoginContainer: {
    marginBottom: 20,
  },
  dividerContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  dividerLine: {
    flex: 1,
    height: 1,
    backgroundColor: '#ccccccff',
  },
  dividerText: {
    marginHorizontal: 10,
    color: '#666',
    fontSize: 14,
  },
  otherLoginButtons: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 10,
  },
  otherLoginButton: {
    alignItems: 'center',
  },
  icon: {
    width: 40,
    height: 40,
    marginBottom: 5,
  },
  otherLoginText: {
    fontSize: 12,
    color: '#333',
  },
  passwordInputContainer: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1, // 底部边框
    borderBottomColor: '#ccccccff', // 底部边框颜色
  },
  passwordInput: {
    flex: 1,
    height: 40,
  },
  eyeIcon: {
    padding: 10,
  },
  eyeIconImage: {
    width: 20,
    height: 20,
  },
});
